//
//  ShopCartVC.m
//  sensen_ios
//
//  Created by pro on 16/2/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ShopCartVC.h"

#import "ShopMessageVC.h" // 消息界面
#import "ConfirmOrderVC.h" // 确认订单页面
#import "ProductDetailsVC.h" // 商品详情界面
// 单元格
#import "CartCell.h"

// 数据
#import "CartProductModel.h"
#import "StoreDiscountModel.h" // 店铺推荐model

// 辅助
#import "ProductInfoHandle.h"


@interface ShopCartVC () <UITableViewDataSource, UITableViewDelegate, AmountModifyViewDelegate>
{
    BOOL _isAllSelected; // 是否全选
    StoreDiscountModel *_discountModel; // 店铺推荐model
}

// 数据
@property (nonatomic, strong) NSMutableArray<CartProductModel *> *itemsAry; // 信息数组，由网络获取
@property (nonatomic, strong) NSMutableArray<CartProductModel *> *selectedItemsAry; // 选中的数组
@property (nonatomic, strong) NSMutableArray<NSNumber *> *boolAry; // 判断是否选中，元素数量应与信息数组相同

// 视图
@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UIView *emptyView; // 没有信息时候的视图

// 结算视图及其子视图
@property (nonatomic, strong) UIView *settlementView; // 结算视图
@property (nonatomic, strong) UIButton *settlementButton; // 结算按钮
@property (nonatomic, strong) UIView *allSelectView; // 全选按钮视图
@property (nonatomic, strong) UILabel *priceLabel; // 合计总价Label
@property (nonatomic, strong) UILabel *notesLabel; // 注释Label

@end

@implementation ShopCartVC

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    [self createRightBarButtonItems]; // 导航栏右侧按钮
    
    [self _createViews]; // 创建视图

    UserModel *user = [CommonCache getUserInfo];
    if (user == nil) { // 未登录
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVc animated:YES completion:nil];
    }
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [self _initData]; // 获取数据

    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:NO];
    if ([SVProgressHUD isVisible]) {
        [SVProgressHUD dismiss];
    }
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main showTabBar];
}
// 创建导航栏右侧按钮
- (void)createRightBarButtonItems {
    
    // 消息按钮
    UIView *messageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 35)];
    messageView.userInteractionEnabled = YES;
    messageView.tag = 1;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
    [messageView addGestureRecognizer:tap];
    // 图标
    UIImageView *messageImgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 20, 20)];
    messageImgView.userInteractionEnabled = YES;
    messageImgView.image = [UIImage imageNamed:@"商城首页_消息"];
    [messageView addSubview:messageImgView];
    // label
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 30, 15)];
    messageLabel.userInteractionEnabled = YES;
    messageLabel.font = FONT(10);
    messageLabel.text = @"消息";
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    [messageView addSubview:messageLabel];
    
    UIBarButtonItem *rightBarButton1 = [[UIBarButtonItem alloc] initWithCustomView:messageView];
    
    // 删除按钮
    UILabel *deleteLabel = [[UILabel alloc] initWithFrame:messageView.frame];
    deleteLabel.userInteractionEnabled = YES;
    deleteLabel.font = FONT(15);
    deleteLabel.text = @"删除";
    deleteLabel.textColor = [UIColor whiteColor];
    deleteLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:deleteLabel];
    deleteLabel.tag = 2;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
    [deleteLabel addGestureRecognizer:tap2];
    UIBarButtonItem *rightBarButton2 = [[UIBarButtonItem alloc] initWithCustomView:deleteLabel];

    NSArray *itemsAry = @[rightBarButton2, rightBarButton1];
    self.navigationItem.rightBarButtonItems = itemsAry;
}

#pragma mark - 获取数据
- (void)_initData {
    // 初始化购物车数组
    _itemsAry = [[NSMutableArray alloc] init];
    _boolAry = [[NSMutableArray alloc] init];
    _selectedItemsAry = [[NSMutableArray alloc] init];
    
    UserModel *user = [CommonCache getUserInfo];
    if (user == nil) { // 未登录
        
        _tableView.hidden = YES;
        _settlementView.hidden = YES;
        _emptyView.hidden = NO;
        
        return;
    } else {
        _tableView.hidden = NO;
        _settlementView.hidden = NO;
        _emptyView.hidden = YES;
    }
    
    NSDictionary *params = @{@"uid":[CommonCache getUserInfo].uid};
    [SVProgressHUD showWithStatus:nil];
    self.view.userInteractionEnabled = NO;
    [BoyeHttpClient post:@"BY_ShoppingCart_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {

        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;

        if (![result isKindOfClass:[NSNull class]]) {
            for (NSDictionary *dic in result) {
                CartProductModel *model = [[CartProductModel alloc] initContentWithDic:dic];
                [_itemsAry addObject:model];
                [_boolAry addObject:@NO]; // 开始默认都是未选中的
            }
        }
        
        // 改变是否全选
        [self _changeAllSelectedState];
        // 根据当前的选中数组来计算总价格，并刷新视图
        [self _changeTotalPrice];

        // 没有数据的时候就隐藏表视图和结算视图
        if (_itemsAry.count == 0 || _itemsAry == nil) {
            _tableView.hidden = YES;
            _settlementView.hidden = YES;
            _emptyView.hidden = NO;
        } else {
            _emptyView.hidden = YES;
            
            // 刷新表视图
            [_tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"购物车查询_error:%@",error);
//        [SVProgressHUD showErrorWithStatus:@"查询失败" withDuration:1.5];
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];

        self.view.userInteractionEnabled = YES;

    }];
    
    
    // 获得店铺推荐数据（传到订单确认页面）
    [BoyeHttpClient post:@"BY_StorePromotion_getInfo" apiVerson:100 params:@{@"store_id":@2} success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"商铺推荐优惠:%@", result);
        // 有数据，对于没数据的直接传给确认订单页面一个nil就好了
        if (![result isKindOfClass:[NSNull class]]) {
            _discountModel = [[StoreDiscountModel alloc] initContentWithDic:result];
            
            // 如果当前时间不在优惠时间区间内，则不给予优惠
            if (!([[NSDate currentTimeStamp] integerValue] >= [_discountModel.start_time integerValue] && [[NSDate currentTimeStamp] integerValue] <= [_discountModel.end_time integerValue])) {
                _discountModel = nil;
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"商铺推荐请求_error:%@", error);
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];

    
}

// 选中数组 懒加载
- (NSMutableArray *)selectedItemsAry {
    if (_selectedItemsAry == nil) {
        _selectedItemsAry = [[NSMutableArray alloc] init];
    }

    return _selectedItemsAry;
}

#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createEmptyView]; // 没有信息时候的视图
    [self _createSettlementView]; // 创建结算视图
    [self _initTableView]; // 创建表视图
    
}
// 创建结算视图
- (void)_createSettlementView {
    // 结算视图
    _settlementView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 49)];
    _settlementView.bottom = SCREEN_HEIGHT - 64;
    [self.view addSubview:_settlementView];
    
    // 子视图
    CGFloat x, y, width, height;
    width = 80;
    height = _settlementView.height;
    y = 0;
    x = _settlementView.width - width;
    // 1.结算按钮
    _settlementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _settlementButton.frame = CGRectMake(x, y, width, height);
    _settlementButton.backgroundColor = RED_COLOR;
    [_settlementButton setTitle:@"结算" forState:UIControlStateNormal];
    [_settlementButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_settlementButton addTarget:self action:@selector(_settlementAction:) forControlEvents:UIControlEventTouchUpInside];
    [_settlementView addSubview:_settlementButton];
    
    // 2.全选视图
    x = 10;
    y = 0;
    width = 80;
    _allSelectView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [_settlementView addSubview:_allSelectView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_allSelectClick)];
    [_allSelectView addGestureRecognizer:tap];
    
    x = 0;
    width = 20;
    height = width;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    imgView.image = [UIImage imageNamed:@"购物车_未选中"];
    [_allSelectView addSubview:imgView];
    imgView.tag = 10;
    imgView.center = CGPointMake(imgView.center.x, _allSelectView.height / 2);

    x = imgView.right + 5;
    width = _allSelectView.width - x;
    height = _allSelectView.height;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    label.userInteractionEnabled = YES;
    label.font = FONT(12);
    label.text = @"全选";
    label.textColor = [UIColor darkGrayColor];
    label.textAlignment = NSTextAlignmentLeft;
    [_allSelectView addSubview:label];
    
    // 3.价格Label
    y = 5;
    width = 120;
    height = 20;
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _priceLabel.font = FONT(15);
    _priceLabel.text = @"合计：￥0.00";
    _priceLabel.textColor = [UIColor darkGrayColor];
    _priceLabel.textAlignment = NSTextAlignmentRight;
    [_settlementView addSubview:_priceLabel];
    _priceLabel.right = _settlementButton.left - 10;
    
    // 4.注释Label
    y = _priceLabel.bottom;
    _notesLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _notesLabel.font = FONT(12);
    _notesLabel.text = @"不含运费";
    _notesLabel.textColor = [UIColor lightGrayColor];
    _notesLabel.textAlignment = NSTextAlignmentRight;
    [_settlementView addSubview:_notesLabel];
    _notesLabel.right = _priceLabel.right;
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - _settlementView.height) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // 注册单元格
    [_tableView registerClass:[CartCell class] forCellReuseIdentifier:@"CartCell"];
}

// 没有信息时候的视图
- (void)_createEmptyView {
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = SCREEN_WIDTH * 0.5;
    CGFloat height = width;
    _emptyView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self.view addSubview:_emptyView];
    
    y = 0;
    width = _emptyView.width * 0.6;
    height = width;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    imgView.image = [UIImage imageNamed:@"购物车为空"];
    [_emptyView addSubview:imgView];
    imgView.center = CGPointMake(_emptyView.center.x, imgView.center.y);
    
    x = 0;
    y = imgView.bottom + 5;
    width = _emptyView.width;
    height = 20;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    label.font = FONT(18);
    label.text = @"您的购物车空空如也";
    label.textColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    label.textAlignment = NSTextAlignmentCenter;
    [_emptyView addSubview:label];
    
    
    _emptyView.center = self.view.center;
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _itemsAry.count;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CartCell *cell = (CartCell *)[tableView dequeueReusableCellWithIdentifier:@"CartCell"];
    cell.amountModifyView.delegate = self;
    // 设置数据
    cell.model = _itemsAry[indexPath.row];
    cell.selectButton.selected = [_boolAry[indexPath.row] boolValue]; // 设置是否选中

    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 取消选中阴影
    
    // 点击进入该商品的详情页
    CartProductModel *model = [_itemsAry objectAtIndex:indexPath.row];
    ProductDetailsVC *vc = [[ProductDetailsVC alloc] init];
    vc.pid = model.p_id;
    
    [self.navigationController pushViewController:vc animated:YES];
}
// 实现此协议方法 左划 会出现删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 结束更新
    [tableView beginUpdates];
    
    // 首先删除数组中的数据
    NSInteger row = indexPath.row; // 找到要删除元素的索引
    CartProductModel *item = [_itemsAry objectAtIndex:row]; // 找到该元素，如果该元素是已经被选中，则在选中数组中也要删除
    if ([self.selectedItemsAry containsObject:item]) {
        [self.selectedItemsAry removeObject:item];
    }
    [_itemsAry removeObject:item];
    
    // 调用删除接口
    NSDictionary *params = @{@"id" : @[item._id]};
    [BoyeHttpClient post:@"BY_ShoppingCart_delete" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"删除失败:%@", error] withDuration:3];
    }];

    [_boolAry removeObjectAtIndex:row]; // 删除bool数组中对应的索引的元素
    
    // 改变是否全选
    [self _changeAllSelectedState];
    // 根据当前的选中数组来计算总价格，并刷新视图
    [self _changeTotalPrice];
    
    // 从表视图中删除
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    // 开始更新
    [tableView endUpdates];
    
//    NSLog(@"%@", self.selectedItemsAry);
//    NSLog(@"%@", self.boolAry);
    
}

     

#pragma mark - 数量修改代理
- (void)amountDidModified:(NSInteger)amount {
    NSInteger modifiedIndex = 0;
    
    // 遍历数据数组，找到数量变更了索引 modifiedIndex，然后修改该索引对应的model并改变其数量，然后取代原来的model，并且如果选中数组中也包含了，则也要取代。最后重新计算价格
    for (int i = 0; i < _itemsAry.count; i++) {
        CartCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];

        NSInteger modifiedAmount = [cell.amountModifyView getAmount];

        CartProductModel *model = _itemsAry[i];
        if (cell == nil) {
            continue;
        }
        if ([model.count integerValue] != modifiedAmount) {
            modifiedIndex = i; // 找到了修改数量的index
            if (amount == 0) {
                [SVProgressHUD showOnlyStatus:@"不能再减了哦,亲" withDuration:2];
                cell.amountModifyView.amount = 1;
                return;
            }
            model.count = [NSString stringWithFormat:@"%li", (long)modifiedAmount];
            [_itemsAry replaceObjectAtIndex:modifiedIndex withObject:model];
            if ([_selectedItemsAry containsObject:model]) {
                [_selectedItemsAry replaceObjectAtIndex:[_selectedItemsAry indexOfObject:model] withObject:model];
            }
            
            break;
        }
    }
    
    // 计算总价格
    [self _changeTotalPrice];
}

#pragma mark - 点击事件
- (void)rightClick:(UITapGestureRecognizer *)tap {
    switch (tap.view.tag) {
        case 1: // 跳转到消息界面
        {
            ShopMessageVC *vc = [[ShopMessageVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2: // 删除事件
            [self _deleteAction];
        default:
            break;
    }
}
// 点击右侧导航栏删除按钮执行（删除选中的单元格）
- (void)_deleteAction {
    
    // 没有选中任何商品，不做操作
    if (self.selectedItemsAry.count == 0) {
        return;
    }
    
    // 结束更新
    [_tableView beginUpdates];
    
    // 首先删除数组中的数据
    // 循环遍历选中数组，并逐一从数据数组中删除对应元素
    NSMutableArray *indexPaths = [NSMutableArray array]; // 需要删除的单元格
    NSMutableArray *cartIdAry = [NSMutableArray array]; // 用于获得购物车id的数组
    NSMutableArray *temp_items = [_itemsAry copy]; // 用于查找索引的数组
    
    for (CartProductModel *item in self.selectedItemsAry) {
        NSInteger row = [temp_items indexOfObject:item];
        NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:0];
        [indexPaths addObject:path];
        [cartIdAry addObject:item._id];
        [_itemsAry removeObject:item];
    }
    
    // 调用删除接口
    NSDictionary *params = @{@"id" : [cartIdAry componentsJoinedByString:@","]};
    [BoyeHttpClient post:@"BY_ShoppingCart_delete" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:2];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"删除失败:%@", error.domain] withDuration:2];
    }];
    
    // 因为把选中数组中的元素全删了，所以要把选中数组置空，bool数组全设为未选中
    [self.selectedItemsAry removeAllObjects];
    [_boolAry removeAllObjects];
    for (int i = 0; i < _itemsAry.count; i ++) {
        [_boolAry addObject:@(NO)];
    }
    
    // 改变是否全选
    [self _changeAllSelectedState];
    // 根据当前的选中数组来计算总价格，并刷新视图
    [self _changeTotalPrice];
    
    // 从表视图中删除
    [_tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    
    // 开始更新
    [_tableView endUpdates];
    
//    NSLog(@"%@", self.selectedItemsAry);
//    NSLog(@"%@", self.boolAry);
}

// 结算
- (void)_settlementAction:(UIButton *)button {

    // 没有选择商品则不能跳转到订单界面
    if (self.selectedItemsAry.count == 0 || self.selectedItemsAry == nil) {
        [SVProgressHUD showOnlyStatus:@"您还没有选择商品呢,亲" withDuration:2];
        return;
    }
    
    
    NSMutableDictionary *parmas = [[NSMutableDictionary alloc] init];
    NSMutableArray *idAry = [[NSMutableArray alloc] init];
    NSMutableArray *countAry = [[NSMutableArray alloc] init];
    for (CartProductModel *model in self.selectedItemsAry) {
        [idAry addObject:model._id];
        [countAry addObject:model.count];
    }
    [parmas setObject:[idAry componentsJoinedByString:@","] forKey:@"id"];
    [parmas setObject:[countAry componentsJoinedByString:@","] forKey:@"count"];
    
    [SVProgressHUD showWithStatus:@"正在检测订单状态"];
    
    [BoyeHttpClient post:@"BY_ShoppingCart_edit" apiVerson:100 params:parmas success:^(AFHTTPRequestOperation *operation, id result) {
        
        NSLog(@"*********购物车修改:%@", result);
        [SVProgressHUD dismiss];
        
        // 进入确认订单页面
        ConfirmOrderVC *vc = [[ConfirmOrderVC alloc] init];
        vc.itemsAry = [self.selectedItemsAry copy];
        vc.discountModel = _discountModel;
        [self.navigationController pushViewController:vc animated:YES];
        
        // 去订单确认页面时要移除全部的属性
        [self _removeAllProperties];
       
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];
    
   
}
// 点击单元格的选中按钮的事件
- (void)selectAction:(UIButton *)button {
    
    // 点击单元格，则使单元格中的选择视图选中
    CartCell *cell = nil;
//    NSLog(@"%@",button.superview);
    UIView *view = button.superview;
    while (![view isKindOfClass:[CartCell class]]) {
        view = [view superview];
    }
    cell = (CartCell *)view;
    NSInteger row = [_tableView indexPathForCell:cell].row;
//    NSLog(@"%i",row);
    // 取出该单元格对应的boolAry中的元素并取反
    BOOL isSelected = [_boolAry[row] boolValue];
    isSelected = !isSelected;
    [_boolAry replaceObjectAtIndex:row withObject:@(isSelected)];
    
    // 选中后则加入到选中数组中，否则从选中数组中删除
    if (isSelected) {
        [self.selectedItemsAry addObject:_itemsAry[row]];
    } else {
        [self.selectedItemsAry removeObject:_itemsAry[row]];
    }
    
    // 改变是否全选
    [self _changeAllSelectedState];
    // 根据当前的选中数组来计算总价格，并刷新视图
    [self _changeTotalPrice];
    
//    NSLog(@"%@", self.selectedItemsAry);
//    NSLog(@"%@", self.boolAry);
    [_tableView reloadData]; // 刷新数据
}
// 全选
- (void)_allSelectClick {
    
    _isAllSelected = !_isAllSelected;

    // 把数据数组中的数据全部放入选中数组中
    self.selectedItemsAry = _isAllSelected ? [_itemsAry mutableCopy] : [NSMutableArray array];
    
    // 改变是否全选
    [self _changeAllSelectedState];
    // 根据当前的选中数组来计算总价格，并刷新视图
    [self _changeTotalPrice];
    
    // 把对应的单元格设为选中或未选中
    [_boolAry removeAllObjects];
    for (int i = 0; i < _itemsAry.count; i ++) {
        [_boolAry addObject:@(_isAllSelected)];
    }
    
    NSLog(@"%@", self.selectedItemsAry);
    NSLog(@"%@", self.boolAry);
    [_tableView reloadData]; // 刷新表视图

}


#pragma mark - 其他方法，简化代码块（重复利用的代码）
// 改变全选按钮的状态
- (void)_changeAllSelectedState {
    if (_itemsAry.count == 0) { // 总数为空
        _isAllSelected = NO;
    } else { // 总数不为空
        _isAllSelected = _itemsAry.count == _selectedItemsAry.count ? YES : NO;
    }
    UIImageView *imgView = [_allSelectView viewWithTag:10];
    imgView.image = [UIImage imageNamed:_isAllSelected ? @"购物车_选中":@"购物车_未选中"];
}
// 根据当前的选中数组来计算总价格，并刷新视图
- (void)_changeTotalPrice {
    CGFloat totalPrice = [ProductInfoHandle countSelectedCartProductTotalPrice:self.selectedItemsAry];
    _priceLabel.text = [NSString stringWithFormat:@"合计：￥%.2lf", totalPrice];
    _priceLabel.textColor = SS_NAVI_ORANGE_COLOR;
    //一 创建NSMutableAttributedString 对象
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:_priceLabel.text];
    // 字体颜色
    [attrString addAttribute:NSForegroundColorAttributeName
                       value:[UIColor darkGrayColor]
                       range:[_priceLabel.text rangeOfString:@"合计："]];
    // 字体
    [attrString addAttribute:NSFontAttributeName
                       value:[UIFont systemFontOfSize:15]
                       range:[_priceLabel.text rangeOfString:@"合计："]];
    _priceLabel.attributedText = attrString;
    _priceLabel.width = [_priceLabel.text getSizeOfString:15].width;
    _priceLabel.right = _settlementButton.left - 10;
}

// 移除全部属性
- (void)_removeAllProperties {
    
    [self.selectedItemsAry removeAllObjects];
    [self.itemsAry removeAllObjects];
    [self.boolAry removeAllObjects];
    _isAllSelected = NO;
    _discountModel = nil;
}



#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
